import crypto from 'crypto'
import jwt from 'jwt-simple'
import {
	tokenExp
} from '../../utils/constants.js'

import encryptPassword from '../../utils/encryptPassword.js';

import validateToken from '../../utils/validateToken.js';
import groupFunc from '../../utils/groupFunc.js';

async function Perform(event) {
	if (event.type === 0) { // 断开团体关系
		if (!event.token) {
			return {
				status: -4,
				errCode: 'TOKEN_INVALID',
				msg: '出错了！'
			}
		}

		try {
			let result = await validateToken(event.token);
			if (result.status != 0) {
				return result;
			}
		} catch (e) {
			return {
				status: -2,
				errCode: 'TOKEN_INVALID',
				// msg: 'token无效'
				msg: '请重新登录'
			}
		}

		await groupFunc.updateGroupParent(event.group_id,"");
	} else if (event.type === 1){ // 建立团体关系
		const {
			group_id,
			parent_id
		} = event;

		let isExist = await groupFunc.checkGroupItem(group_id,{parent_id});
		if (isExist === true) {
			return {
				status: 0,
				msg: "已是下属团体了！"
			}
		}

		await groupFunc.updateGroupParent(group_id,parent_id);
	} else if (event.type === 2) { // 更新是否开放成员注册
		const {
			group_id,
			is_reg
		} = event;
		await groupFunc.updateGroupItem(group_id,{ is_reg });
	} else if (event.type === 3) { // 更新团体
		let {
			group_id,
			name,
			label,
			is_reg,
			is_split
		} = event;

		name = name.replace(/\s*/g,"");
		if ( name.length < 3 ) {
			return {
				status: -1,
				msg: "团体名称长度不能小于3！"
			}
		}

		await groupFunc.updateGroupItem(group_id,{
			name,
			label,
			is_reg,
			is_split
		});
	}

	return {
		status: 0,
		msg: "更新成功！"
	}
}

export {
	Perform as main
}
